package com.ruoyi.jihuo.api;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.jihuo.utils.RetryUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class GetItemApiImpl implements GetItemApi {

    private static final int MAX_ATTEMPTS = 1;
    private static final int SLEEP_MILLIS = 1000;

    @Override
    public String getItem(String source, String id) {
        if (!"tmall".equals(source)) {
            return "";
        }
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        return tryGetItem2(id, client, mediaType);
    }

    private String tryGetItem1(String id, OkHttpClient client, MediaType mediaType) {
        String msg = "商品" + id;
        try {
            return RetryUtil.retry(() -> {
                try {
                    return getItemOne(id, client, mediaType);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }, MAX_ATTEMPTS, SLEEP_MILLIS, msg);
        } catch (Exception e1) {
            log.error("{}，获取失败", msg);
            throw new RuntimeException(msg + " 的信息 获取失败");

        }
    }

    private String tryGetItem2(String id, OkHttpClient client, MediaType mediaType) {
        String msg = "商品" + id;
        try {
            return RetryUtil.retry(() -> {
                try {
                    return getItemTwo(id, client, mediaType);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }, MAX_ATTEMPTS, SLEEP_MILLIS, msg);
        } catch (Exception e2) {
            log.error("{}，获取失败", msg);
            throw new RuntimeException(msg + " 的信息 获取失败");
        }

    }

    //接口一
    public String getItemOne(String id, OkHttpClient client, MediaType mediaType) throws IOException {
        JSONObject json = new JSONObject();
        json.put("numIid", id);

        RequestBody body = RequestBody.create(mediaType, json.toJSONString());
        Request request = new Request.Builder()
                .url("http://8.142.162.128:30005/sl6mk2xe/api/item/gettb")
                .post(body)
                .addHeader("appid", "8000020386")
                .addHeader("appsecret", "epZvPAs8EKmQ54NQGnMa")
                .addHeader("Content-Type", "application/json")
                .build();
        return executeRequest(client, request);
    }

    //接口二
    public String getItemTwo(String id, OkHttpClient client, MediaType mediaType) throws IOException {
        JSONObject json = new JSONObject();
        json.put("itemId", id);

        RequestBody body = RequestBody.create(mediaType, json.toJSONString());
        Request request = new Request.Builder()
                .url("http://152.136.39.132:29376/sl9du2nz/api/item/gettb")
                .method("POST", body)
                .addHeader("appid", "1000010216")
                .addHeader("appsecret", "z7u1x0pz2srpxad9o1dk")
                .addHeader("Content-Type", "application/json")
                .build();
        return executeRequest(client, request);
    }

    //统一处理异常和响应校验
    private String executeRequest(OkHttpClient client, Request request) throws IOException {
        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            if (response == null) {
                throw new RuntimeException("response 为 null");
            }
            if (!response.isSuccessful()) {
                String errorMsg = response.body() != null ? response.body().string() : "无响应体";
                throw new RuntimeException("请求失败，状态码：" + response.code() + "，错误信息：" + (StringUtils.isBlank(errorMsg) ? "null" : errorMsg));
            }
            if (response.body() == null) {
                throw new RuntimeException("响应体为 null");
            }

            JSONObject jsonObject = JSONObject.parseObject(responseBody);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            if (StringUtils.isNotBlank(code) && !"000000".equals(code)){
                throw new RuntimeException(msg);
            }
            return responseBody;
        }
    }
}